'use client'

import { useState, useRef, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Checkbox } from '@/components/ui/checkbox'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Progress } from '@/components/ui/progress'
import { Badge } from '@/components/ui/badge'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { useToast } from '@/hooks/use-toast'
import { Download, Upload, FileSpreadsheet, AlertCircle, CheckCircle, Info, X, ArrowLeft } from 'lucide-react'
import Link from 'next/link'
import { useAuth } from '@/hooks/use-auth'
import { SimpleDeviceSelector } from '@/components/simple-device-selector'
import { DataImportDialog } from '@/components/data-import-dialog'

// 专业定义
const SPECIALTIES = [
  { code: 'piping', name: '配管专业', subSpecialties: [
    { code: 'drainage', name: '给排水' },
    { code: 'fire', name: '消防' },
    { code: 'process', name: '工艺' },
    { code: 'piping', name: '配管' }
  ]},
  { code: 'electrical', name: '电气专业' },
  { code: 'hvac', name: '暖通专业' },
  { code: 'communication', name: '通信专业' },
  { code: 'instrumentation', name: '仪表专业' }
]

interface DeviceTypeMapping {
  device_id: string;
  classification_code: string;
  classification_name: string;
  specialty: string;
  name: string;
}


export function TemplateManager() {
  const { user, loading: authLoading, error: authError } = useAuth();
  const { toast } = useToast();

  const [deviceTypes, setDeviceTypes] = useState<DeviceTypeMapping[]>([]);
  const [selectedSpecialty, setSelectedSpecialty] = useState<string>('');
  const [selectedSubSpecialty, setSelectedSubSpecialty] = useState<string>('');
  const [selectedObjectCategory, setSelectedObjectCategory] = useState<string>('');
  const [loading, setLoading] = useState(false);
  
  // 导出选项
  const [includeExamples, setIncludeExamples] = useState(true);
  const [maxRows, setMaxRows] = useState(100);
  
  // 数据导入对话框状态
  const [importDialogOpen, setImportDialogOpen] = useState(false);

  // 加载设备类型（与专业导航栏使用相同的数据源）
  const loadDeviceTypes = async () => {
    try {
      const response = await fetch('/api/device-hierarchy-by-name');
      const data = await response.json();
      if (data.success) {
        // 将层次结构数据转换为设备类型数组，与专业导航栏保持一致
        const allDevices = data.data.flatMap((hierarchy: any) => 
          hierarchy.devices.map((device: any) => ({
            device_id: device.device_id,
            classification_code: device.classification_code,
            classification_name: device.classification_name,
            specialty: device.specialty,
            name: device.name
          }))
        );
        setDeviceTypes(allDevices);
      }
    } catch (error) {
      console.error('加载设备类型失败:', error);
    }
  };

  useEffect(() => {
    loadDeviceTypes();
  }, []);

  // 导出模板
  const handleExportTemplate = async () => {
    if (!user) {
      toast({
        title: '错误',
        description: '请先登录',
        variant: 'destructive'
      });
      return;
    }

    if (!selectedSpecialty || !selectedObjectCategory) {
      toast({
        title: '错误',
        description: '请选择专业和对象类',
        variant: 'destructive'
      });
      return;
    }

    // 如果是配管专业，需要选择子专业
    if (selectedSpecialty === 'piping' && !selectedSubSpecialty) {
      toast({
        title: '错误',
        description: '配管专业请选择子专业',
        variant: 'destructive'
      });
      return;
    }

    // 根据选中的专业和对象类找到对应的第一个设备（因为同对象类的设备模板结构相同）
    // selectedSpecialty是专业代码，需要转换为专业名称
    const specialtyName = SPECIALTIES.find(s => s.code === selectedSpecialty)?.name;
    
    const selectedDevice = deviceTypes.find(dt => 
      dt.specialty === specialtyName && 
      dt.classification_name === selectedObjectCategory
    );
    
    if (!selectedDevice) {
      toast({
        title: '错误',
        description: '找不到选中的对象类信息',
        variant: 'destructive'
      });
      return;
    }

    setLoading(true);
    try {
      const response = await fetch('/api/template/export', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          classificationCode: selectedDevice.classification_code,
          specialty: selectedDevice.specialty, // 使用设备数据中的专业名称
          objectCategory: selectedDevice.classification_name, // 使用设备数据中的对象类名称
          includeExamples,
          maxRows
        })
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        const errorMessage = errorData.error || `导出失败 (${response.status})`;
        throw new Error(errorMessage);
      }

      // 下载文件
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      // 更新的模板命名格式：专业-对象类.xlsx
      // selectedDevice数据结构：
      // - specialty: 专业（如"配管专业"）  
      // - classification_name: 对象类（如"冷却水喷淋装置"）
      const fileName = `${selectedDevice.specialty}-${selectedDevice.classification_name}.xlsx`;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);

      toast({
        title: '成功',
        description: '模板导出成功',
      });

    } catch (error) {
      toast({
        title: '错误',
        description: error instanceof Error ? error.message : '导出失败',
        variant: 'destructive'
      });
    } finally {
      setLoading(false);
    }
  };


  // 获取角色描述
  const getRoleDescription = (roleCode: string) => {
    const roleMap: Record<string, string> = {
      'A': '系统管理员（全部权限）',
      'E': '设计人员（设计数据）',
      'P': '采购人员（采购数据）',
      'M': '监测人员（监测数据）',
      'C': '施工人员（施工数据）',
      'O': '建设人员（建设数据）',
      'R': '运维人员（运维数据）',
      'V': '查看人员（只读权限）'
    };
    return roleMap[roleCode] || '未知角色';
  };

  return (
    <>
      <div className="container mx-auto p-6 space-y-6">
        {/* 返回链接 */}
        <div className="mb-6">
          <Link href="/">
            <Button variant="outline" className="gap-2">
              <ArrowLeft className="h-4 w-4" />
              返回首页
            </Button>
          </Link>
        </div>
        
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold">模板管理</h1>
            <p className="text-gray-600 mt-2">导出Excel模板，批量导入设备数据</p>
          </div>
        {user && (
          <Badge variant="outline" className="text-sm">
            {getRoleDescription(user.role_code)}
          </Badge>
        )}
      </div>

      {/* 设备选择器 - 只选择专业和对象类 */}
      <SimpleDeviceSelector
        selectedSpecialty={selectedSpecialty}
        selectedSubSpecialty={selectedSubSpecialty}
        selectedObjectCategory={selectedObjectCategory}
        onSpecialtyChange={setSelectedSpecialty}
        onSubSpecialtyChange={setSelectedSubSpecialty}
        onObjectCategoryChange={setSelectedObjectCategory}
        hideDeviceTypeSelection={true}
      />

      <Tabs defaultValue="export" className="space-y-4">
        <TabsList className="grid grid-cols-2 w-fit">
          <TabsTrigger value="export">模板导出</TabsTrigger>
          <TabsTrigger value="import">数据导入</TabsTrigger>
        </TabsList>

        {/* 模板导出 */}
        <TabsContent value="export">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Download className="w-5 h-5" />
                导出Excel模板
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="flex items-center space-x-2">
                  <Checkbox 
                    id="include-examples" 
                    checked={includeExamples}
                    onCheckedChange={setIncludeExamples}
                  />
                  <Label htmlFor="include-examples">包含示例数据</Label>
                </div>
                
                <div>
                  <Label htmlFor="max-rows">最大行数</Label>
                  <Input
                    id="max-rows"
                    type="number"
                    value={maxRows}
                    onChange={(e) => setMaxRows(Number(e.target.value))}
                    min={10}
                    max={1000}
                    className="w-32"
                  />
                </div>
              </div>

              {/* 用户状态 */}
              {!user ? (
                <Alert>
                  <AlertCircle className="h-4 w-4" />
                  <AlertDescription>
                    请先<a href="/login" className="text-blue-600 hover:text-blue-800 underline">登录</a>后再导出模板
                  </AlertDescription>
                </Alert>
              ) : (
                <div className="text-sm text-gray-600">
                  当前用户：{user.full_name} ({user.role_name})
                </div>
              )}

              <Button 
                onClick={handleExportTemplate} 
                disabled={!selectedSpecialty || !selectedObjectCategory || (selectedSpecialty === 'piping' && !selectedSubSpecialty) || loading || !user}
                className="w-full"
              >
                {loading ? '导出中...' : !user ? '请先登录' : (!selectedSpecialty || !selectedObjectCategory || (selectedSpecialty === 'piping' && !selectedSubSpecialty)) ? '请完成选择' : '导出Excel模板'}
              </Button>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 数据导入 */}
        <TabsContent value="import">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Upload className="w-5 h-5" />
                导入Excel数据
              </CardTitle>
              <CardDescription>
                上传Excel文件创建设备实例
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* 用户状态 */}
              {!user ? (
                <Alert>
                  <AlertCircle className="h-4 w-4" />
                  <AlertDescription>
                    请先<a href="/login" className="text-blue-600 hover:text-blue-800 underline">登录</a>后再导入数据
                  </AlertDescription>
                </Alert>
              ) : (
                <div className="text-sm text-gray-600">
                  当前用户：{user.full_name} ({user.role_name})
                </div>
              )}

              {/* 导入说明 */}
              <Alert>
                <Info className="h-4 w-4" />
                <AlertDescription>
                  先导出Excel模板，填写数据后导入。设备实例将添加到选择的设备类下。
                </AlertDescription>
              </Alert>

              {/* 导入按钮 */}
              <Button 
                onClick={() => setImportDialogOpen(true)}
                disabled={!selectedSpecialty || !selectedObjectCategory || (selectedSpecialty === 'piping' && !selectedSubSpecialty) || !user}
                className="w-full"
                size="lg"
              >
                <Upload className="w-4 h-4 mr-2" />
                {!user ? '请先登录' : (!selectedSpecialty || !selectedObjectCategory || (selectedSpecialty === 'piping' && !selectedSubSpecialty)) ? '请完成选择' : '开始数据导入'}
              </Button>

            </CardContent>
          </Card>

        </TabsContent>
      </Tabs>

      {/* 数据导入对话框 */}
      {selectedSpecialty && selectedObjectCategory && (selectedSpecialty !== 'piping' || selectedSubSpecialty) && user && (() => {
        const specialtyName = SPECIALTIES.find(s => s.code === selectedSpecialty)?.name;
        const selectedDevice = deviceTypes.find(dt => 
          dt.specialty === specialtyName && 
          dt.classification_name === selectedObjectCategory
        );
        
        return (
          <DataImportDialog
            open={importDialogOpen}
            onOpenChange={(open) => {
              setImportDialogOpen(open);
              if (!open) {
                // 导入完成后刷新设备列表
                loadDeviceTypes();
              }
            }}
            specialty={specialtyName || ''}
            objectCategory={selectedObjectCategory}
            userRole={user.role_code}
            classificationCode={selectedDevice?.classification_code}
          />
        );
      })()}
    </div>
    </>
  );
}